package cn.e4j.modular.crm.controller;

import cn.e4j.core.base.controller.BaseController;
import cn.e4j.core.common.exception.BizExceptionEnum;
import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.PageReData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.reqres.response.SuccessResponseData;
import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.shiro.ShiroUser;
import cn.e4j.core.util.StringUtils;
import cn.e4j.modular.crm.entity.EsaaT;
import cn.e4j.modular.crm.service.EsaaTService;
import cn.e4j.modular.crm.service.EsabTService;
import cn.e4j.modular.crm.service.Esai100Service;
import cn.e4j.modular.system.model.EmailProperties;
import cn.e4j.modular.system.service.SysMailService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/crm/esai100")
public class Esai100Controller extends BaseController {
    @Autowired
    private EsaaTService esaaTService;

    @Autowired
    private EsabTService esabTService;

    @Autowired
    private SysMailService sysMailService;

    @Autowired
    private Esai100Service esai100Service;

    /**
     * 跳转至问题维护主界面
     *
     * @return
     */
    @RequiresPermissions("crm:esai100:init")
    @RequestMapping(value = {"", "/init"})
    public String index() {
        return "/pc/crm/esai100.html";
    }

    @RequiresPermissions("crm:esai100:init")
    @RequestMapping("/getList")
    @ResponseBody
    public ResponseData getList(@DtoParam DtoWapper dtoWapper) {

        Dto inDto = dtoWapper.getDto();
        Page<Object> page = dtoWapper.getPage();

        ShiroUser shiroUser = ShiroKit.getUser();
        String TYPE = shiroUser.getTYPE();

        // 外部用户只允许查看自己的问题列表
        if (TYPE.equals("1")) {
            Dto esab = esabTService.getEsabByEsab003(shiroUser.getID());
            if (esab == null) {
                return new ErrorResponseData(0, "当前用户不是客户负责人");
            }
            inDto.put("ESAA001", esab.getString("ESAB001"));
        }
        // 内部员工只查看处理人是自己的
        if (TYPE.equals("0")) {
            inDto.put("ESAA010", shiroUser.getID());
        }

        List<String> ESAASTUS_LIST;
        if (!StringUtils.isEmpty(inDto.getString("ESAASTUS_LIST"))) {
            ESAASTUS_LIST = new ArrayList<>();
            String[] states = inDto.getString("ESAASTUS_LIST").split(",");
            Collections.addAll(ESAASTUS_LIST, states);
            inDto.put("ESAASTUS_LIST", ESAASTUS_LIST);
        }

        List<Map<String, Object>> list = esaaTService.getEsaalist(page, inDto);
        if (TYPE.equals("1")) {
            list.forEach(map -> map.put("userType", "1"));
        }
        return new PageReData(page, list);
    }

    @RequiresPermissions("crm:esai100:add")
    @RequestMapping("/add")
    @ResponseBody
    public ResponseData add(EsaaT esaaT) {
        if (esaaTService.existedTheParams(esaaT)) {
            return new ErrorResponseData(BizExceptionEnum.EXISTED_THE_PARAMS.getCode(),
                    BizExceptionEnum.EXISTED_THE_PARAMS.getMessage());
        } else {
            esaaTService.add(esaaT);
        }

        //  发送邮件
        try {
            EmailProperties properties = esai100Service.getEmailProperties(esaaT, "EMPLOYEE");
            if (properties != null) {
                sysMailService.sendEmailWithAttach(properties);
            }
        } catch (Exception e) {
            return new SuccessResponseData();
        }

        // 添加邮件日志
        esai100Service.addMailLog(esaaT, "EMPLOYEE");

        return SUCCESS_TIP;
    }

    /**
     * 获取新增时的默认数据
     *
     * @return
     */
    @RequiresPermissions("crm:esai100:add")
    @RequestMapping("/getAddData")
    @ResponseBody
    public ResponseData getAddData() {
        // 获取当前登录用户（客户主要联系人即默认提单人）
        ShiroUser shiroUser = ShiroKit.getUser();
        String ID = shiroUser.getID();
        String account = shiroUser.getACCOUNT();
        Dto outDto = Dtos.newDto();

        // 获取注册信息
        Dto esab = esai100Service.getEsabData();
        if (esab != null) {
            outDto.put("ESAA001", esab.getString("ESAB001")); // 客户编号
            outDto.put("ESAA001_NAME", esab.getString("ESAB030")); // 客户名称
            outDto.put("ESAA002", esab.getString("ESAB003_NAME"));  // 问题提单人员
            outDto.put("ESAA010", esab.getString("ESAB025")); // 维保服务人员（即问题处理人员）
            outDto.put("ESAA010_NAME", esab.getString("ESAB025_NAME")); // 维保服务人员名称
        }
        return new SuccessResponseData(outDto);
    }

    @RequiresPermissions("crm:esai100:edit")
    @RequestMapping("/edit")
    @ResponseBody
    public ResponseData edit(EsaaT esaaT) {
        esaaTService.edit(esaaT);
        return SUCCESS_TIP;
    }

    @RequiresPermissions("crm:esai100:del")
    @RequestMapping("/del")
    @ResponseBody
    public ResponseData delRow(EsaaT esaaT) {
        esaaTService.delete(esaaT);
        return SUCCESS_TIP;
    }

    @RequiresPermissions("crm:esai100:del")
    @RequestMapping("/delBatch")
    @ResponseBody
    public ResponseData delRowsBatch(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<EsaaT> esaaTList = inDto.getReqList(EsaaT.class);
        esaaTService.deleteBatch(esaaTList);
        return SUCCESS_TIP;
    }

    @RequiresPermissions("crm:esai100:edit")
    @RequestMapping("/changeStatus")
    @ResponseBody
    public ResponseData changeStatus(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<EsaaT> esaaTList = inDto.getReqList(EsaaT.class);
        esaaTService.changeStatusBatch(esaaTList);
        EsaaT firEsaaT = esaaTList.get(0);
        String state = firEsaaT.getESAASTUS();

        // 如果是退回操作，则需要发送邮件通知内部用户
        if (state.equals("3")) {
            EmailProperties properties = esai100Service.getEmailProperties(firEsaaT, "EMPLOYEE");
            properties.setSubject("客户问题提报 -- 您的处理被退回");
            try {
                sysMailService.sendEmailWithAttach(properties);
            } catch (MessagingException e) {
                return SUCCESS_TIP;
            }
            // 添加邮件日志
            esai100Service.addMailLog(firEsaaT, "EMPLOYEE");
        }
        if (state.equals("2")) { // 问题被受理时给客户发邮件
            EmailProperties properties = esai100Service.getEmailProperties(firEsaaT, "CLIENT");
            properties.setSubject("客户问题提报 -- 您的问题已被受理，正在处理中");
            try {
                sysMailService.sendEmailWithAttach(properties);
            } catch (MessagingException e) {
                return SUCCESS_TIP;
            }
            // 添加邮件日志
            esai100Service.addMailLog(firEsaaT, "CLIENT");
        }
        if (state.equals("4")) { // 问题结案时给客户和员工都发邮件
            for (EsaaT esaaT : esaaTList) {
                EmailProperties properties = esai100Service.getEmailProperties(esaaT, "BOTH");
                properties.setSubject("客户问题提报 -- 问题结案");
                try {
                    sysMailService.sendEmailWithAttach(properties);
                } catch (MessagingException e) {
                    return SUCCESS_TIP;
                }
                // 添加邮件日志
                esai100Service.addMailLog(esaaT, "CLIENT");
                esai100Service.addMailLog(esaaT, "EMPLOYEE");
            }
        }
        return SUCCESS_TIP;
    }

    @RequiresPermissions("crm:esai100:edit")
    @RequestMapping("/transferBatch")
    @ResponseBody
    public ResponseData transfer(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<EsaaT> esaaTList = inDto.getReqList(EsaaT.class);
        JSONArray jsonArray = JSON.parseArray(inDto.getString("_jsonStr_"));
        String oldEsaa010 = jsonArray.getJSONObject(0).getString("ESAA010_NAME");
        esaaTService.transferBatch(esaaTList);

//         转派后需要发送邮件
        for (EsaaT esaaT : esaaTList) {
            EmailProperties properties = esai100Service.getEmailProperties(esaaT, "EMPLOYEE");
            properties.setSubject("客户问题提报 -- 问题转派");
            properties.setText(properties.getText() + "\n" + "原处理人员：" + oldEsaa010);
            try {
                sysMailService.sendEmailWithAttach(properties);
            } catch (MessagingException e) {
                return SUCCESS_TIP;
            }

            // 添加邮件日志
            esai100Service.addMailLog(esaaT, "EMPLOYEE");
        }
        return SUCCESS_TIP;
    }

    @RequiresPermissions("crm:esai100:edit")
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public ResponseData getUserInfo(@DtoParam DtoWapper dtoWapper) {
        // 获取当前登录用户（客户主要联系人即默认提单人）
        ShiroUser shiroUser = ShiroKit.getUser();
        Dto outDto = Dtos.newDto();
        outDto.put("USER_TYPE", shiroUser.getTYPE());
        outDto.put("USER_ID", shiroUser.getID());
        return new SuccessResponseData(outDto);
    }
}
